JavaScript - invoke JS code in iframe from parent page

revision:


Content

contentWindow property contentDocument property window.postMessage() window.parent.postMessage() practical examples()


contentWindow property

top

The "contentWindow property" returns the HTML iframeElement's window object. You can use this Window object to access the iframe's document and its internal DOM.

This attribute is read-only, but its properties can be manipulated like the global Window object.

Syntax: iframeElement.contentWindow;

The contentWindow property allows to access the window object of the iframe, which in turn allows you to execute JavaScript code within it.

Value: a window object

Code examples:

        // Get the iframe element
             const iframe = document.getElementById('myIframe');
        
        // Access the window object of the iframe
            const iframeWindow = iframe.contentWindow;
        
        // Execute JavaScript code within the iframe
            iframeWindow.postMessage('Hello from parent page!', '*');
           
        // Turn the color of the iframe blue
            const iframe = document.querySelector("iframe").contentWindow;
            iframe.document.querySelector("body").style.backgroundColor = "blue";

        // from parent -> iframe    
                // in the parent page:
                    const iframe = document. getElementById("iframe");
                    iframe.contentWindow.postMessage("some message, "*");
                // in the iframe:
                    window.onmessage = function(e){
                        if(e.data === "some message"){
                            alert("it works!")
                        }
                    };

        //  from iframe -> Page
                // in parent page:
                    window.onmessage = function(e){
                        if(e.data === "some message"){
                            alert("it works!")
                        }
                    };
                // in iframe
                    window.top.postMessage('from iframe', "*");


    

Examples

parent page

demo_1 iframe is used as content.




click text in iframe to change color

code:
                    <div>
                        <h4>parent page</h4>
                        <div class="spec">
                            <button onclick= "change_iframe_content()"> Change iframe_Content </button>
                            <br><br><br>
                            <!-- iframe window -->
                            <iframe class="spec" id="frame"  src="demo_1.html" frameborder="1"> </iframe>
                            <p class="spec">click text u=in iframe to change color</p>
                        </div>
                    </div>
                    <script>
                        change_iframe_content = () => {
                            // contentWindow Property - returns Window Object
                            const if_doc = document.getElementById("frame").contentWindow;
                            // Accessing document -> div -> Changing InnerHTML
                            if_doc.document.getElementsByTagName('div')[0].innerHTML = "you have changed the 
                            content of the iframe";
                            const iframe = document.querySelector("#frame").contentWindow;
                            iframe.document.querySelector("body").style.backgroundColor = "green";    
                        }
                    </script>
                

parent page

demo_2 iframe is used as content.

click the button to change the background color of the document contained in the iframe.

code
                    <div>
                        <h4>parent page</h4>
                        <div>
                            <iframe id="frame1" src="demo_2.html" frameborder="1"></iframe>
                            <p>click the button to change the background color of the document 
                            contained in the iframe.</p>
                            <button onclick="iframeF1()">try it</button>
                            <p id="iframe_demo"></p>
                        </div>
                    </div>
                    <script>
                        function iframeF1(){
                            var x = document.getElementById("frame1");
                            var y = (x.contentWindow || x.contentDocument);
                            if (y.document)y = y.document;
                            y.body.style.backgroundColor = "red"
                        }
                    </script>
                


parent page

demo_2 iframe is used as content.

Click the button to change the background color of the document contained in the iframe.

code:
                    <div>
                        <h4>parent page</h4>
                        <iframe id="frame2" src="demo_2.html"></iframe>
                        <p>Click the button to change the background color of the document
                         contained in the iframe.</p>
                        <p id="iframe_demo1"></p>
                        <button onclick="iframeF2()">try it</button>
                    </div>
                    <script>
                        function iframeF2() {
                            var x = document.getElementById("frame2");
                            var y = x.contentWindow.document;
                            y.body.style.backgroundColor = "green";
                        }
                    </script>
                

parent page

demo_2 iframe is used as content.

click inside the iframe

code:
                    <div>
                        <h4>parent page</h4>
                        <iframe id="frame3" src="demo_2.html" width="400" height="150"></iframe>
                        <p>click inside the iframe</p>
                        <p id="iframe_demo2" style="color: red"></p>
                    </div>
                    <script>
                        window.onload = function() {
                            var iframe = document.getElementById('frame3');
                            var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
                            iframeDocument.addEventListener("click", function() {
                                document.getElementById("iframe_demo2").innerHTML = "iframe clicked!";
                                document.getElementById("frame3").style.backgroundColor = "violet";
                            });
                        }
                    </script>
                

contentDocument property

top

The "contentDocument property" returns the Document object generated from the frame or iframe element. This property can be used by the host window to access the Document object associated with the frame or iframe element.

Syntax: iframeElement.contentDocument;

If the iframe's content is from the same origin as the parent page, you can also use the contentDocument property to access the document object of the iframe. This allows you to manipulate the iframe's HTML and execute JavaScript code within it.

Code examples:

        // Get the iframe element
            const iframe = document.getElementById('myIframe');

        // Access the document object of the iframe
            const iframeDocument = iframe.contentDocument;

        // Execute JavaScript code within the iframe
            const iframeScript = document.createElement('script');
            iframeScript.textContent = 'console.log("Hello from parent page!");';
            iframeDocument.body.appendChild(iframeScript);

        // turn the iframe blue
            const iframeDocument = document.querySelector("iframe").contentDocument;
            iframeDocument.body.style.backgroundColor = "blue";            
    

Examples

parent page

demo_3 iframe is used as content.

code:
                    <div>
                        <h4>parent page</h4>
                        <iframe id="frame4" src="demo_3.html"></iframe>
                    </div>
                    <script>
                        const iframe1 = document.getElementById("myIframe1");
                        iframe1.addEventListener('load', function() {
                            // Loaded, so we can dynamically modify iframe
                            iframe1.style.border = '0.5vw solid red';
                            iframe1.width = 400;
                            iframe1.height = 100;
                            // Can also modify DOM, attributes, etc
                            iframe1.style.backgroundColor = "pink";
                            
                        });
                    </script>
                

parent page

demo_2 iframe is used as content.

Click the button to change the background color of the document contained in the iframe.

code:
                    <div>
                        <h4>parent page</h4>
                        <iframe id="frame5" src="demo_2.html"></iframe>
                        <p>Click the button to change the background color of the document contained 
                        in the iframe.</p>
                        <p id="frame_demo_one"></p>
                        <button onclick="myFrame1()">try it</button>
                    </div>
                    <script>
                        function myFrame1() {
                            var x = document.getElementById("frame5");
                            var y = (x.contentWindow || x.contentDocument);
                            if (y.document)y = y.document;
                            y.body.style.backgroundColor = "indigo";
                        }
                    </script>
                


parent page

demo_2 iframe is used as content.

Click the button to change the background color of the document contained in the iframe.

code:
                    <div>
                        <h4>parent page</h4>
                        <iframe id="frame6" src="demo_2.html"></iframe>
                        <p>Click the button to change the background color of the document 
                        contained in the iframe.</p>
                        <p id="frame_demo_two"></p>
                        <button onclick="myFrame2()">try it</button>
        
                    </div>
                    <script>
                        function myFrame2() {
                            var x = document.getElementById("frame6");
                            var y = x.contentDocument;
                            y.body.style.backgroundColor = "yellow";
                            }
                    </script>
            

parent page

demo_2 iframe is used as content.





code:
                    <div>
                        <h4>parent page</h4>
                        <iframe src="demo_2.html"  id="frame7" height="150" width="400"></iframe> <br><br>
                        <button onclick="myFrame3()">Submit</button><br><br>
                    </div> 
                    <script>
                        function myFrame3() { 
                            var iframeID = document.getElementById("frame7"); 
                            var iframeCW = (iframeID.contentWindow || iframeID.contentDocument);
                            if (iframeCW.document)iframeCW = iframeCW.document;
                                iframeCW.body.style.border = "5px solid black";
                        } 
                    </script>
                

window.postMessage()

top

The "window.postMessage" method is a secure way to enable communication between two windows (or tabs) that belong to different origins (domains). It allows scripts from one window to safely pass messages to another window, even if they originate from different domains. This is particularly useful for embedding third-party widgets, iframes, or cross-origin communication within your web application.

Syntax:otherWindow.postMessage(message, targetOrigin, [transfer]);

Parameters:

message: the data to be sent to the other window. It can be a string, an object, or any other JSON-serializable /data.

targetOrigin: s1pecifies the target window's origin. To enhance security, this parameter should be set to the specific origin of the target window (e.g., "https://example.com"). You can also use "*" to allow communication with any origin, but this is less secure.

transfer (Optional): an array of Transferable objects (e.g., ArrayBuffer, MessagePort) that should be transferred instead of cloned when sent to the other window. This parameter is useful for improving performance when dealing with large data.

options (optional): an optional object containing a transfer field with a sequence of transferable objects to transfer ownership of, and a optional targetOrigin field with a string which restricts the message to the limited targets only.

Syntax examples:

        postMessage(message)
        postMessage(message, options)
        postMessage(message, targetOrigin)
        postMessage(message, targetOrigin, transfer)
    

window.parent.postMessage()

top

The "window.parent.postMessage" method is similar to "window.postMessage", but it is used specifically within an embedded iframe to communicate with its parent window.

Syntax: parent.postMessage(message, targetOrigin, [transfer]);

Parameters:

message: he data to be sent to the parent window.

targetOrigin: specifies the parent window's origin.

transfer (Optional): an array of Transferable objects (e.g., ArrayBuffer, MessagePort) that should be transferred instead of cloned when sent to the other window. This parameter is useful for improving performance when dealing with large data.


practical examples

top

Example 1

demo_3 iframe is used as content.

parent page

code:
                <div>
                    <h4>parent page</h4>
                    <iframe id="myIframe2" src="demo_3.html"></iframe>        
                </div>
                <script>
                    const iframe2 = document.getElementById('myIframe2');
                    iframe2.addEventListener('load', function() {
                        // Scripts MUST wait until iframe is loaded  
                        // Option 1: External script
                        const script = document.createElement('script');
                        script.src = 'core.js';
                        iframe2.contentDocument.body.appendChild(script);
                           // Option 2: Inline script 
                        const script1 = document.createElement('script1');
                        script1.innerHTML = `
                            // Can safely access iframe DOM here
                        `;
                        iframe2.contentDocument.body.appendChild(script1); 
            
                        });
                </script>
            

Example 2

demo_3 iframe is used as content.

parent page

code:
                <div>
                    <h4>parent page</h4>
                    <iframe id="myIframe3" src="demo_3.html" frameborder="0"></iframe>        
                </div>
                <script>
                    const iframe3 = document.getElementById('myIframe3');
                    iframe3.addEventListener('load', function() {
                        // Loaded, so we can dynamically modify iframe
                        iframe3.style.border = '1vw dotted blue';
                        iframe3.width = 400;
                        iframe3.height = 150;
                        iframe3.style.backgroundColor = "lightblue";
                        // Can also modify DOM, attributes, etc
                    });
                    
                </script>
            

Example 3

demo_3 iframe is used as content.

parent page




code:
                <div>
                    <h4>parent page</h4>
                    <button onclick="change_iframe()">Change iframe_Content</button><br><br><br>
                    <iframe id="myIframe4" src="demo_3.html" frameborder="1"></iframe>    
                </div>
                <script>
                    change_iframe = () => {
                        const if_doc1 = document.getElementById("myIframe4").contentWindow;
                        if_doc1.document.getElementsByTagName('div')[0].innerHTML = "content has been changed";  
                        if_doc1.document.getElementsByTagName('div')[0].style.color = 'red';
                        if_doc1.document.getElementsByTagName('div')[0].style.backgroundColor = 'green';
                        if_doc1.document.getElementsByTagName('body')[0].style.backgroundColor = 'grey';
                    }
                </script>
            

Example 4

demo_3 iframe is used as content.

parent page


code:
                <div class="spec">
                    <h4>parent page</h4>
                    <iframe id="myIframe5" src="demo_3.html" frameborder="1"></iframe><br<br><br>  
                    <button onclick="getIframeContent()">get iframe content</button>
                    <p id="demo"></p>      
                </div>
                <script>
                    function getIframeContent() {
                        let frameObj = document.getElementById("myIframe5");
                        let frameContent = frameObj.contentWindow.document.body.innerHTML;
                        document.getElementById("demo").innerHTML = "frame content : " + frameContent;
                    }          
                   
                </script>
            

Example 5

demo_4 iframe is used as content.

code:
                <div>
                    <button onclick="SetFrameBGToRed ()">Set frame background to red</button>
                    <iframe id="myFrame" src="demo_4.html" width="250px" height="200px"></iframe>
                </div>
                <script>
                    function SetFrameBGToRed () {
                        var italicTag = document.createElement ("i");
                        italicTag.innerHTML = "Italic text";
                        var frame = document.getElementById ("myFrame");
                        var frameDoc = frame.contentWindow.document;
                        frameDoc.body.style.backgroundColor = "red";
                }
               </script>
            

Example 6

demo_5 iframe is used as content.


code:
                <div>
                    <iframe id="taal" src="demo_5.html" width= "1200px" height="400px" frameborder="0"></iframe><br>
                    <button onclick="setNed()">select Dutch</button>
                    <button onclick="setEng()">select English</button>
                    <button onclick="setChi()">select Chinese</button>
                 </div>
                 <script>
                     function setNed(){
                         var taal = document.getElementById("taal");
                         var kiesTaal = taal.contentWindow.document;
                         kiesTaal.getElementById("ned").style.display="flex";
                     }
                     function setEng(){
                         var taal1 = document.getElementById("taal");
                         var kiesTaal1 = taal1.contentWindow.document;
                         kiesTaal1.getElementById("eng").style.display="flex";
                     }
                     function setChi(){
                         var taal2 = document.getElementById("taal");
                         var kiesTaal2 = taal2.contentWindow.document;
                         kiesTaal2.getElementById("chn").style.display="flex";
                     }
                
                 </script>
            

Example 7

demo_6 iframe is used as content.


Click the respective buttons to make the texts disappear and reappear (= toggle)

code:
            <div>
                <iframe id="taal1" src="demo_6.html" width= "1200px" height="150px" frameborder="1"></iframe><br>
                <button onclick="setNed1()">Dutch</button>
                <button onclick="setEng1()">English</button>
                <button onclick="setChi1()">Chinese</button>
                <p>Click the respective buttons to make the texts disappear and reappear (= toggle)</p>
             </div>
             <script>
                 function setNed1(){
                     var taal_a = document.getElementById("taal1");
                     var kiesTaal_a = taal_a.contentWindow.document;
                     let nl = kiesTaal_a.getElementsByClassName("nederlands")[0];
                     nl.style.display == "block" ? nl.style.display = "none" : nl.style.display = "block"; 
                     
                 }
                 function setEng1(){
                     var taal_a = document.getElementById("taal1");
                     var kiesTaal_a = taal_a.contentWindow.document;
                     let en = kiesTaal_a.getElementsByClassName("english")[0];
                     en.style.display == "block" ? en.style.display = "none" : en.style.display = "block"; 
                 }
                 function setChi1(){
                    var taal_a = document.getElementById("taal1");
                     var kiesTaal_a = taal_a.contentWindow.document;
                     let cn = kiesTaal_a.getElementsByClassName("chinese")[0];
                     cn.style.display == "block" ? cn.style.display = "none" : cn.style.display = "block"; 
                 }
            
             </script>
         


Example 8

demo_7 iframe is used as content.


code:
        <div class="spec">
            <iframe id="taal2" src="demo_7.html" width= "1400px" height="250px" frameborder="1"></iframe><br>
            <button onclick="setNed2()">Dutch</button>
            <button onclick="setEng2()">English</button>
            <button onclick="setChi2()">Chinese</button>
          <script>
           function setNed2(){
                var x, y, z,i;
                var taal = document.getElementById("taal2");
                var doc = taal.contentWindow.document;
                x = doc.querySelectorAll(".nederlands");
                for (i = 0; i < x.length; i++) {
                    x[i].style.display = "flex";
                }
                
                y = doc.querySelectorAll(".english");
                for (i = 0; i < y.length; i++) {
                    y[i].style.display = "none";
                }
            
                z = doc.querySelectorAll(".chinese");
                for (i = 0; i < z.length; i++) {
                    z[i].style.display = "none";
                }
            }
            function setEng2(){
                var x, y, z,i;
                var taal = document.getElementById("taal2");
                var doc = taal.contentWindow.document;
                x = doc.querySelectorAll(".english");
                for (i = 0; i < x.length; i++) {
                    x[i].style.display = "flex";
                }
                
                y = doc.querySelectorAll(".nederlands");
                for (i = 0; i < y.length; i++) {
                    y[i].style.display = "none";
                }
            
                z = doc.querySelectorAll(".chinese");
                for (i = 0; i < z.length; i++) {
                    z[i].style.display = "none";
                }
            }
            function setChi2(){
                var x, y, z,i;
                var taal = document.getElementById("taal2");
                var doc = taal.contentWindow.document;
                x = doc.querySelectorAll(".chinese");
                for (i = 0; i < x.length; i++) {
                    x[i].style.display = "flex";
                }
                
                y = doc.querySelectorAll(".english");
                for (i = 0; i < y.length; i++) {
                    y[i].style.display = "none";
                }
            
                z = doc.querySelectorAll(".nederlands");
                for (i = 0; i < z.length; i++) {
                    z[i].style.display = "none";
                }
            }
          
         </script>